<script>
import axios from "axios";
export default {
  name: 'LoginPage',
  data() {
    return {
      type: 'log',
      log_form: {
        username: "",
        email: "",
        password: "",
        ver_code: "",
        auto_log: false
      },
      reg_form: {
        username: "",
        email: "",
        password: "",
        db_password: "",
        email_code: "",
        check: false,
      },
      email_loading: false,
      send_time: 0,

      reg_loading: false,
      log_loading: false
    }
  },
  methods: {
    createCanvas() {
      const canvas = document.getElementById("myCanvas");
      const ctx = canvas.getContext("2d");
      const width = window.innerWidth;
      const height = window.innerHeight;

      canvas.width = width;
      canvas.height = height;

      const particles = [];
      const particleCount = 300;
      const particleSpeed = 1;
      const particleSize = 2;
      const maxDistance = 100;
      const lightningColor = "#fff";

      class Particle {
        constructor() {
          this.x = Math.random() * width;
          this.y = Math.random() * height;
          this.color = "#fff";
          this.angle = Math.random() * 360;
          this.speed = Math.random() * particleSpeed;
          this.opacity = Math.random() * 0.5 + 0.5;
        }

        update() {
          this.x += Math.cos(this.angle) * this.speed;
          this.y += Math.sin(this.angle) * this.speed;

          if (this.x < 0 || this.x > width || this.y < 0 || this.y > height) {
            this.x = Math.random() * width;
            this.y = Math.random() * height;
          }
        }

        draw() {
          ctx.beginPath();
          ctx.arc(this.x, this.y, particleSize, 0, Math.PI * 2);
          ctx.fillStyle = `rgba(255, 255, 255, ${this.opacity})`;
          ctx.fill();
        }
      }

      function createParticles() {
        for (let i = 0; i < particleCount; i++) {
          particles.push(new Particle());
        }
      }

      function drawConnections() {
        for (let i = 0; i < particles.length; i++) {
          for (let j = i + 1; j < particles.length; j++) {
            const dx = particles[i].x - particles[j].x;
            const dy = particles[i].y - particles[j].y;
            const distance = Math.sqrt(dx * dx + dy * dy);

            if (distance < maxDistance) {
              ctx.beginPath();
              ctx.moveTo(particles[i].x, particles[i].y);
              ctx.lineTo(particles[j].x, particles[j].y);
              ctx.strokeStyle = lightningColor;
              ctx.lineWidth = 0.2 * (1 - distance / maxDistance);
              ctx.stroke();
              ctx.closePath();
            }
          }
        }
      }

      function animate() {
        ctx.clearRect(0, 0, width, height);

        for (const particle of particles) {
          particle.update();
          particle.draw();
        }

        drawConnections();

        requestAnimationFrame(animate);
      }

      document.addEventListener("mousemove", (e) => {
        const mouseX = e.clientX;
        const mouseY = e.clientY;

        for (const particle of particles) {
          const dx = mouseX - particle.x;
          const dy = mouseY - particle.y;
          const distance = Math.sqrt(dx * dx + dy * dy);

          if (distance < maxDistance) {
            particle.angle = Math.atan2(dy, dx);
            particle.speed = 5;
          } else {
            particle.speed = Math.random() * particleSpeed;
          }
        }
      });

      createParticles();
      animate();
    },
    goReg() {
      this.type = 'reg'
      this.clearLogForm()
    },
    goLog() {
      this.type = 'log'
      this.clearRegForm()
    },
    login() {
      if (this.log_form.username === '') {
        this.$message.warning("请输入用户名或邮箱")
        return
      }

      if (this.log_form.password === '') {
        this.$message.warning("请输入密码")
        return
      }

      if (this.log_form.ver_code === '') {
        this.$message.warning("请输入验证码")
        return
      }
      let formData = new FormData()
      formData.append("username", this.log_form.username)
      formData.append("password", this.log_form.password)
      formData.append("code", this.log_form.ver_code)
      formData.append("auto", this.log_form.auto_log)

      this.log_loading = true
      axios.post("/api/user/log", formData)
          .then(resp => {
            this.log_loading = false
            if (resp.data.code === 0) {
              this.$message.success(resp.data.msg)
              let user = resp.data.data
              user.avatar = '/api/res/'+user.avatar
              this.$store.commit('setUser',user)
              this.$router.replace("/index/home")
            } else {
              this.$message.warning(resp.data.msg)
              this.switchCode()
            }
          }).catch(err => this.$message.error(err))
    },
    switchCode() {
      document.getElementsByClassName('verification')[0].src = "/api/code?" + Math.random()
    },
    regis() {
      if (!this.checkUsername()) {
        this.$message.warning("用户名必须是6-18位数,以字母开头,不包含特殊字符")
        return
      }
      if (!this.checkPassword()) {
        this.$message.warning("密码必须是8-18位数,以字母开头,不包含特殊字符")
        return
      }

      if (!this.checkEmail()) {
        this.$message.warning("请输入正确的邮箱")
        return
      }

      if (!this.checkDbPassword()) {
        this.$message.warning("两次输入的密码不一致")
        return
      }

      if (!this.checkCode()) {
        this.$message.warning("验证码不能为空")
        return
      }
      if (this.reg_form.check) {
        let formData = new FormData()
        formData.append("username", this.reg_form.username)
        formData.append("password", this.reg_form.password)
        formData.append("email", this.reg_form.email)
        formData.append("code", this.reg_form.email_code)
        this.reg_loading = true
        axios.post("/api/user/reg", formData)
            .then(resp => {
              this.reg_loading = false
              if (resp.data.code === 0) {
                this.$message.success(resp.data.msg)
                this.log_form.username = this.reg_form.username
                this.goLog()
              } else {
                this.$message.warning(resp.data.msg)
              }
            }).catch(err => this.$message.error(err))
      } else {
        this.$message.warning("请勾选协议")
      }

    },
    checkUsername() {
      return this.reg_form.username !== '' && /^[a-zA-Z][a-zA-Z0-9]{5,18}$/.test(this.reg_form.username)
    },
    checkPassword() {
      return this.reg_form.password !== '' && /^[a-zA-Z][a-zA-Z0-9]{7,18}$/.test(this.reg_form.username)
    },
    checkDbPassword() {
      return this.reg_form.db_password !== '' && this.reg_form.password === this.reg_form.db_password
    },
    checkCode() {
      return this.reg_form.email_code !== ''
    },
    checkEmail() {
      return this.reg_form.email !== '' && /\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/.test(this.reg_form.email);
    },
    sendCode(e) {
      if (this.checkEmail()) {
        this.email_loading = true
        axios.get("/api/code/" + this.reg_form.email).then(resp => {
          this.email_loading = false
          if (resp.data.code === 0) {
            this.$message.success(resp.data.msg)
            e.target.innerText = "已发送(60)"
            e.target.disabled = true
            e.target.style.cursor = "not-allowed"
            let time = 59
            let inter = setInterval(function () {
              e.target.innerText = `已发送(${time})`
              time--
              if (time < 0) {
                e.target.innerText = "重新发送"
                e.target.disabled = false
                e.target.style.cursor = "pointer"
                clearInterval(inter)
              }
            }, 1000)
          } else {
            this.$message.warning(resp.data.msg)
          }
        }).catch(err => this.$message.error(err))
      } else {
        this.$message.warning("请输入正确的邮箱")
      }
    },
    clearRegForm() {
      this.reg_form = {
        username: "",
        email: "",
        password: "",
        db_password: "",
        email_code: "",
        check: false,
      }
    },
    clearLogForm() {
      this.log_form = {
        username: "",
        email: "",
        password: "",
        ver_code: "",
        auto_log: false
      }
    }
  },
  mounted() {


    this.createCanvas()

  }
}
</script>

<template>
  <div class="box">
    <div class="login_header">
      <el-avatar :src="require('@/assets/logo.png')" class="logo"></el-avatar>
      <div class="logo_txt">Strelitzia</div>
    </div>
    <el-card class="log_card" v-if="type === 'log'" v-loading="log_loading">
      <div class="title_box">登 录</div>
      <div class="tip_reg_box">还没有一个账号?<a class="go_reg" @click="goReg">去注册</a></div>
      <el-input class="txt_input" placeholder="用户名或邮箱" v-model="log_form.username" clearable></el-input>
      <el-input class="txt_input" type="password" placeholder="密码" v-model="log_form.password" clearable></el-input>
      <div class="code_box">
        <el-input class="txt_input code_input " placeholder="验证码" v-model="log_form.ver_code"></el-input>
        <img class="verification" alt="更换验证码" :src="'/api/code'" @click="switchCode">
      </div>
      <el-checkbox class="check_box" v-model="log_form.auto_log">自动登录30天</el-checkbox>
      <div style="width: 100%">
        <button class="log_btn" @click="login">登 录</button>
      </div>
    </el-card>

    <el-card class="reg_card" v-else v-loading="reg_loading">
      <div class="title_box">注 册</div>
      <div class="tip_reg_box">已有一个账号!<a class="go_reg" @click="goLog">去登陆</a></div>
      <el-input class="txt_input" placeholder="用户名" v-model="reg_form.username" clearable></el-input>
      <el-input class="txt_input" placeholder="邮箱" v-model="reg_form.email" clearable></el-input>
      <el-input type="password" class="txt_input" placeholder="密码" v-model="reg_form.password" clearable></el-input>
      <el-input type="password" class="txt_input" placeholder="确认密码" v-model="reg_form.db_password"
                clearable></el-input>
      <div class="code_box">
        <el-input class="txt_input code_input" placeholder="邮箱验证码" v-model="reg_form.email_code"></el-input>
        <button class="send_btn" @click="sendCode" v-loading="email_loading">发送验证码</button>
      </div>
      <el-checkbox class="check_box" v-model="reg_form.check">我同意条款和政策</el-checkbox>
      <div style="width: 100%">
        <button class="log_btn" @click="regis">注 册</button>
      </div>
    </el-card>
    <canvas id="myCanvas"></canvas>
    <div class="login_footer">版权所有©支持盗版</div>
  </div>
</template>

<style>
.box {
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
}

canvas {
  height: 100%;
  width: 100%;
  display: block;
  background-image: url("../assets/img/天空 云 阳光的光线 风景图片_彼岸图网.jpg");
  background-size: cover;
}

.login_header {
  position: absolute;
  width: 100%;
  top: 0;
  height: 53px;
  background-color: rgba(255, 255, 255, 0.8); /* 设置背景颜色并添加透明度 */
  border-radius: 10px;

  .el-avatar {
    background: transparent;
  }
}

.login_footer {
  position: absolute;
  width: 100%;
  bottom: 0;
  height: 50px;
  background-color: rgba(255, 255, 255, 0.8); /* 设置背景颜色并添加透明度 */
  border-radius: 10px;
  text-align: center;
  line-height: 50px;
  font-weight: bold;
  cursor: pointer;
}

.logo {
  width: 50px;
  margin-top: 2px;
  margin-left: 60px;
  float: left;
}

.logo_txt {
  float: left;
  width: 120px;
  margin-left: 10px;
  line-height: 53px;
  color: #409EFF;
  font-size: 22px;
  font-weight: bold;
}

.log_card, .reg_card {
  position: absolute;
  top: 130px;
  right: 90px;
  border-radius: 20px;
  height: 480px;
  width: 400px;
  background-color: rgba(255, 255, 255, 0.8); /* 设置背景颜色并添加透明度 */

}

.title_box {
  width: 100%;
  height: 75px;
  font-weight: bold;
  line-height: 90px;
  margin-left: 30px;
  color: rgb(37, 61, 78);
  font-size: 40px;
}

.reg_card {
  top: 66px;
  height: 600px;
}

.tip_reg_box {
  margin-left: 30px;
  font-size: 15px;
  color: rgba(37, 61, 78, 0.5);
}

.go_reg {
  margin-left: 5px;
  color: #409EFF;
}

.go_reg:hover {
  color: orange;
}

.txt_input {
  margin-left: 20px;
  margin-top: 20px;
  width: 320px;
  .el-input__inner {
    height: 50px;
    width: 320px;
  }
}

.code_box {
  .el-input {
    width: 140px;
    float: left;
  }
}

.code_input {

  .el-input__inner {
    height: 50px;
    width: 140px;
  }
}

.verification {
  margin-top: 20px;
  margin-left: 20px;
  width: 100px;
  height: 50px;
  border-radius: 10px;
}

.send_btn {
  margin-top: 20px;
  margin-left: 20px;
  height: 50px;
  width: 100px;
  border-radius: 10px;
  border: none;
  background-color: rgb(37, 61, 78);
  color: white;
  font-size: 15px;
}

.check_box {
  margin-left: 20px;
  margin-top: 20px;
  font-size: 15px;
}

.log_btn {
  float: right;
  margin-top: 20px;
  margin-right: 30px;
  height: 50px;
  width: 103px;
  border-radius: 10px;
  border: none;
  background-color: rgb(37, 61, 78);
  color: white;
  font-size: 15px;
  font-weight: bold;
}

.send_btn:hover, .log_btn:hover {
  background-color: #3BB77E;
  cursor: pointer;
}

.log_btn:hover {
  margin-top: 17px;
}
</style>